const CONFIG = require('../../../../common/config');
const CODE = require('../../../../common/code');
const async = require('async');
const superagent = require('superagent');
const userCenterService = require('../../../service/userCenterService');



const userRouterUtil = (function () {
    function userRouterUtil() {

    }

    /**
     * 第三方微信登录(app 网站)
     *
     * @author 王俊
     * @date 2018-07-19
     *
     *
     * @param {Object} option
     * @param {Object} option.device
     * @param {Object} option.platform
     * @param {Object} option.nickName
     * @param {Object} option.avatarUrl
     * @param {Object} option.field1
     * @param {Object} option.field2
     * @param {Object} option.field3
     * @param {Object} option.field4
     * @param {Object} option.field5
     * @param {Function} callback   回调函数
     *                      error
     *                      data
     */
    userRouterUtil.loginByThirdPlatform = function (option, callback) {
        const totalTasks = [];

        // 1. 重组数据, 并调用服务登录
        totalTasks.push(function (callback) {

            const opt = {
                device: option.device,
                unionId: option.field1,
                openId: option.field2,
                accountType: option.platform,
                wxInfo: {
                    nickName: option.nickName,
                    avatarUrl: option.avatarUrl
                }
            };
            if(!opt.openId) {
                opt.openId = option.field3;
                opt.accountType = 50; // 网站
            }
            if(!opt.unionId || !opt.openId) {
                return callback('参数错误', null);
            }
            userCenterService.wxLoginAndAutoRegister(opt, function (error, data) {
                 return callback(error, data);
            });
        });

        // 2. 调用服务获取用户资料
        totalTasks.push(function (data, callback) {
            /**
             * @param {Number} option.device            设备标识
             * @param {Number} option.userId            用户唯一标识
             * @param {Number} option.withOrganization  是否获取用户组织信息
             * @param {String} option.withReward        是否获取用户收益信息
             * @param {Number} option.withWallet        是否获取用户秀米钱包信息
             *
             */
            const opt = {
                device: option.device,
                userId: data.userId,
                withOrganization: 1,
                withReward: 1,
                withWallet: 1
            };
            userCenterService.getUserInfo(opt, function (error, userInfo) {
                data.retData = userInfo;
                return callback(error, data);
            });
        });


        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data.retData);
        });


    };

    


    return userRouterUtil;
})();

module.exports = userRouterUtil;